package cn.wolfcode.wolf2w.search.Controller;


import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.search.domian.*;
import cn.wolfcode.wolf2w.search.query.SearchQueryObject;
import cn.wolfcode.wolf2w.search.service.ISearchService;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 根据所选的查询条件，进行全文搜索查询
 */
@RestController
public class SearchController {
    @Autowired
    private IDestinationService destinationService;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private ITravelService travelService;
    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private ISearchService searchService;

    @GetMapping("/q")
    public Object search(SearchQueryObject qo) throws Exception {
        // 将前台传过来的参数转换成utf-8格式
        String key = URLDecoder.decode(qo.getKeyword(), "UTF-8");
        qo.setKeyword(key);

        switch (qo.getType()){
            case SearchQueryObject.TYPE_DEST: // 目的地
                return searchDest(qo);
            case SearchQueryObject.TYPE_STRATEGY: // 攻略
                return searchStrategy(qo);
            case SearchQueryObject.TYPE_TRAVEL: // 游记
                return searchTravel(qo);
            case SearchQueryObject.TYPE_USER:  // 用户
                return searchUser(qo);
                default:
                    return searchAll(qo); // 全部
        }
    }


    private Object searchUser(SearchQueryObject qo) {
        // 通过页面输入关键词进行全文搜索（结果需要高亮显示）
        // 全文搜索 + 高亮显示
        Page<UserInfo> page = searchService.searchWithHighlight(UserInfoEs.INDEX_NAME, UserInfoEs.TYPE_NAME,
                UserInfo.class, qo, "info", "city");

        HashMap<String,Object> map = new HashMap<>();
        map.put("page",page);
        map.put("qo",qo);
        return JsonResult.success(map);
    }

    private Object searchTravel(SearchQueryObject qo) {
        // 通过页面输入关键词进行全文搜索（结果需要高亮显示）
        // 全文搜索 + 高亮显示
        Page<Travel> page = searchService.searchWithHighlight(TravelEs.INDEX_NAME, TravelEs.TYPE_NAME,
                Travel.class, qo, "title", "summary");

        HashMap<String,Object> map = new HashMap<>();
        map.put("page",page);
        map.put("qo",qo);
        return JsonResult.success(map);
    }

    private Object searchStrategy(SearchQueryObject qo) {
        // 通过页面输入关键词进行全文搜索（结果需要高亮显示）
        // 全文搜索 + 高亮显示
        Page<Strategy> page = searchService.searchWithHighlight(StrategyEs.INDEX_NAME, StrategyEs.TYPE_NAME,
                Strategy.class, qo, "title", "subTitle", "summary");

        HashMap<String,Object> map = new HashMap<>();
        map.put("page",page);
        map.put("qo",qo);
            return JsonResult.success(map);
    }

    // 查所有
    private Object searchAll(SearchQueryObject qo) {
        SearchResultVO vo = new SearchResultVO();
        long total = 0L; // 搜索结果总条数
        Page<Strategy> sts = searchService.searchWithHighlight(StrategyEs.INDEX_NAME, StrategyEs.TYPE_NAME,
                Strategy.class, qo, "title", "subTitle", "summary");
        vo.setStrategys(sts.getContent());
        total = total + sts.getTotalElements(); // 攻略分页总记录数

        Page<Travel> ts = searchService.searchWithHighlight(TravelEs.INDEX_NAME, TravelEs.TYPE_NAME,
                Travel.class, qo, "title", "summary");
        vo.setTravels(ts.getContent());
        total = total + ts.getTotalElements();

        Page<UserInfo> us = searchService.searchWithHighlight(UserInfoEs.INDEX_NAME, UserInfoEs.TYPE_NAME,
                UserInfo.class, qo, "info", "city");
        vo.setUsers(us.getContent());
        total = total + us.getTotalElements();

        Page<Destination> ds = searchService.searchWithHighlight(DestinationEs.INDEX_NAME, DestinationEs.TYPE_NAME,
                Destination.class, qo, "name", "info");
        vo.setDestinations(ds.getContent());
        total = total + ds.getTotalElements();

        vo.setTotalResult(total);

        HashMap<String,Object> map = new HashMap<>();
        map.put("result",vo);
        map.put("qo",qo);
        return JsonResult.success(map);
    }
    // 查目的地
    private Object searchDest(SearchQueryObject qo) {

        Destination destination = destinationService.queryByName(qo.getKeyword());

        // 创建vo对象 封装数据
        SearchResultVO vo = new SearchResultVO();
        // 创建map集合，供页面显示
        HashMap<String,Object> map = new HashMap<>();
        // 判断查询输入keyword是不是目的地
        if (destination != null){
            // result : 游记  用户  攻略
            // 通过目的地查询相关游记
            List<Travel> travelList = travelService.queryByDestName(qo.getKeyword());
            // 通过目的地查询相关用户信息
            List<UserInfo> userInfoList = userInfoService.queryByDestName(qo.getKeyword());
            // 通过目的地查询相关游记信息
            List<Strategy> strategyList = strategyService.queryByDestName(qo.getKeyword());
            // 将信息封装进vo封装
            vo.setStrategys(strategyList);
            vo.setTravels(travelList);
            vo.setUsers(userInfoList);

            // 计算出用户 游记 攻略的
            long total = travelList.size() + userInfoList.size() + strategyList.size();
            vo.setTotalResult(total);
        }
            map.put("result",vo);
            map.put("dest",destination);
            map.put("qo",qo);
        return JsonResult.success(map);
    }
}
